package cn.com.alibaba.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;

import cn.com.alibaba.dao.UserDao;
import cn.com.alibaba.domain.User;
import cn.com.alibaba.utils.HibernateUtils;
import cn.com.alibaba.utils.JdbcUtils;

public class UserDaoImpl implements UserDao {

	private QueryRunner qr = new QueryRunner();
	
	public User getUserByLogin(String loginName, String loginPwd) {
//		Connection conn = JdbcUtils.getConnectionWithTransaction();
//		String sql = "select * from S_User where loginName = ? and loginPwd = ? ";
//		try {
//			User user = qr.query(conn, sql, new BeanHandler<User>(User.class),loginName,loginPwd);
//			System.out.println(user);
//			return user;
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			throw new RuntimeException("根据登录名，密码查询用户失败！");
//		}
		Session session = (Session) HibernateUtils.getCurrentSession();
		//Transaction bt = session.beginTransaction();
		
		Criteria cri = session.createCriteria(User.class);
		cri.add(Restrictions.eq("loginName", loginName));
		cri.add(Restrictions.eq("loginPwd", loginPwd));
		User user = null;
		try {
			user = (User) cri.uniqueResult();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//bt.rollback();
			throw new RuntimeException("根据登录名，密码查询用户失败！");
		}
		
		//bt.commit();
		HibernateUtils.close();
		return user;
	}

	public List<User> getUserlistByCondition(String condition, Object[] parms) {
//		Connection conn = JdbcUtils.getConnectionWithTransaction();
//		String sql = "select * from S_User where 1=1 " + condition;
//		try {
//			List<User> list = qr.query(conn, sql, new BeanListHandler<User>(User.class),parms);
//			return list;
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			throw new RuntimeException("根据条件查询用户列表失败！");
//		}
		
		Session session = (Session) HibernateUtils.getCurrentSession();
		//Transaction bt = session.beginTransaction();
		int i = 0;
	    SQLQuery query = session.createSQLQuery("select * from t_user where 1=1 " + condition);
	    for(Object s:parms){
	    	
	    	query.setParameter(i++, s);
	    }
		query.addEntity(User.class);
		List<User> list = null;
		try {
			list = query.list();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//bt.rollback();
			throw new RuntimeException("根据条件查询用户列表失败！");
		}
		
		//bt.commit();
		HibernateUtils.close();
		return list;
	}

	public void addUser(User user) {
//		Connection conn = JdbcUtils.getConnectionWithTransaction();
//		String sql =" INSERT INTO s_user             "+
//					"	(                            "+
//					"	userName,                    "+
//					"	loginName,                   "+
//					"	loginPwd,                    "+
//					"	sex,                         "+
//					"	birthday,                    "+
//					"	education,                   "+
//					"	telephone,                   "+
//					"	interest,                    "+
//					"	path,                        "+
//					"	filename,                    "+
//					"	remark                       "+
//					"	)                            "+
//					"	VALUES                       "+
//					"	(?,?,?,?,?,?,?,?,?,?,?) ";
//
//		try {
//		    qr.update(conn, sql,user.getUserName(),user.getLoginName(),user.getLoginPwd(),
//		    		user.getSex(),user.getBirthday(),user.getEducation(),user.getTelephone(),user.getInterest(),user.getPath(),
//		    		user.getFilename(),user.getRemark());
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			throw new RuntimeException("保存用户失败！");
//		}
		Session session = (Session) HibernateUtils.getCurrentSession();
		//Transaction bt = session.beginTransaction();
		
		try {
			session.save(user);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//bt.rollback();
			throw new RuntimeException("保存用户失败！");
		}
		
		//bt.commit();
		//session.close();
		HibernateUtils.close();
	}

	public User getUserByUserId(Integer id) {
//		Connection conn = JdbcUtils.getConnectionWithTransaction();
//		String sql = "select * from S_User where userId = ? ";
//		try {
//			User user = qr.query(conn, sql, new BeanHandler<User>(User.class),id);
//			System.out.println(user);
//			return user;
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			throw new RuntimeException("根据用户id查询用户失败！");
//		}
		Session session = (Session) HibernateUtils.getCurrentSession();
		//Transaction bt = session.beginTransaction();
		
		Criteria cri = session.createCriteria(User.class);
		cri.add(Restrictions.eq("userID", id));
		User user = null;
		try {
			user = (User) cri.uniqueResult();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//bt.rollback();
			throw new RuntimeException("根据用户id查询用户失败！");
		}
		
		//bt.commit();
		HibernateUtils.close();
		return user;
	}

	public void deleteUserByUserId(Integer id) {
//		Connection conn = JdbcUtils.getConnectionWithTransaction();
//		String sql = "delete from S_User where userId = ? ";
//		try {
//			qr.update(conn, sql, id);
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			throw new RuntimeException("根据用户id删除用户失败！");
//		}
		Session session = (Session) HibernateUtils.getCurrentSession();
		//Transaction bt = session.beginTransaction();
		
		Criteria cri = session.createCriteria(User.class);
		cri.add(Restrictions.eq("userID", id));
		User user = null;
		
		try {
			user = (User) cri.uniqueResult();
			session.delete(user);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//bt.rollback();
			throw new RuntimeException("根据用户id删除用户失败！");
		}
		
		//bt.commit();
		//session.close();
		HibernateUtils.close();
	}

	public void updateUser(User user) {
//		Connection conn = JdbcUtils.getConnectionWithTransaction();
//		String sql = "  UPDATE  s_user            "+
//			         "  SET                       "+
//			         "  userName = ? ,            "+
//			         "  loginName = ? ,           "+
//			         "  loginPwd = ? ,            "+
//			         "  sex = ? ,                 "+
//			         "  birthday = ? ,            "+
//			         "  education = ? ,           "+
//			         "  telephone = ? ,           "+
//			         "  interest = ?,             "+
//			         "  path = ?  ,                "+
//			         "  filename = ?,             "+
//			         "  remark = ?                "+
//			         "  WHERE                     "+
//			         "  userID = ?       ";
//
//
//		try {
//		    qr.update(conn, sql,user.getUserName(),user.getLoginName(),user.getLoginPwd(),
//		    		user.getSex(),user.getBirthday(),user.getEducation(),user.getTelephone(),user.getInterest(),user.getPath(),
//		    		user.getFilename(),user.getRemark(),user.getUserID());
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			throw new RuntimeException("更新用户失败！");
//		}
		
		Session session = (Session) HibernateUtils.getCurrentSession();
		//Transaction bt = session.beginTransaction();
		try {
			session.update(user);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//bt.rollback();
			throw new RuntimeException("更新用户失败！");
		}
			
		//bt.commit();
		//session.close();
		HibernateUtils.close();
	}

}
